<template>
  <section class="todoapp">
    <TodoHeader @add="add"></TodoHeader>
    <TodoMain :list='list' @change='change' @del='del' @checkAll='checkAll'></TodoMain>
    <TodoFooter :list="list" @clear="clear"></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
import { reactive, ref, watch } from 'vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  setup(props) {
    const list = reactive(
      JSON.parse(localStorage.getItem('todosmvc')) || []
    )
    const change = id => {
      // list[index].done = !list[index].done
      const checkout = list.find(item => item.id === id)
      checkout.done = !checkout.done
    }
    // 删除
    const del = index => {
      list.splice(index, 1)
    }
    // 添加
    const add = (name) => {
      list.unshift({
        id: Date.now(),
        name,
        done: false
      })
    }
    // 全选
    const checkAll = (value) => {
      list.forEach(item => item.done = value)
    }
    // 清除
    const data = ref(null)
    const clear = () => {
     return reactive(
      data.value = list.filter(item => !item.done)
     )
    }
    // 本地存储
    watch(list, (value) => {
      localStorage.setItem('todosmvc', JSON.stringify(value))
    })
    return {
      list,
      change,
      del,
      add,
      checkAll,
      clear,
      data
    }
  }
}
</script>

<style></style>
